package com.tengits.mqttmonitor.rnlibs.alarm;

import static com.tengits.mqttmonitor.rnlibs.mqttclient.MQTTClientLibraryModule.randInt;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

public class AlarmLibraryModule extends ReactContextBaseJavaModule implements LifecycleEventListener {
    private static final String TAG = "ReactNative";
    private ReactContext mReactContext;
    private BroadcastReceiver mBroadcastReceiver;
    private static int ALARM_START_ID = randInt(1000, 9999);
    public AlarmLibraryModule(ReactApplicationContext reactContext) {
        super(reactContext);
        mReactContext = reactContext;
        mReactContext.addLifecycleEventListener(this);

        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, final Intent intent) { // 所有任务完成后，都会发广播过来
                String msg = intent.getStringExtra("msg");
                long intervalMillis = intent.getLongExtra("intervalMillis", 0);
                if (intervalMillis != 0) {
                    AlarmManagerUtil.setAlarmTime(context, System.currentTimeMillis() + intervalMillis,
                            intent);
                }
                int id = intent.getIntExtra("id", 0);
                String extraData = intent.getStringExtra("extra");
                WritableMap map = Arguments.createMap();
                map.putInt("id", id);
                map.putString("msg", msg);
                map.putString("extra", extraData);
                map.putString("clientRef", intent.getStringExtra("clientRef"));
                sendEvent(mReactContext, "alarm_event", map);
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AlarmManagerUtil.ALARM_ACTION);
        mReactContext.registerReceiver(mBroadcastReceiver, intentFilter);
    }

    @NonNull
    @Override
    public String getName() {
        return "AlarmLibraryModule";
    }

    @ReactMethod
    public void addListener(String eventName) {
        // Set up any upstream listeners or background tasks as necessary
    }
    @ReactMethod
    public void removeListeners(Integer count) {
        // Remove upstream listeners, stop unnecessary background tasks
    }

    private void sendEvent(ReactContext reactContext,
                           String eventName,
                           @Nullable WritableMap params) {
        if(!reactContext.hasActiveReactInstance()) {
            return;
        }
        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }

    @ReactMethod
    public void setAlarm(int flag, int hour, int minute, int
            week, String tips, String extraData, String ClientRef, Promise promise) {
        int id = ALARM_START_ID;
        ALARM_START_ID += 1;
        AlarmManagerUtil.setAlarm(mReactContext, flag, hour, minute, id, week, tips, extraData, ClientRef);
        promise.resolve(id);
    }

    @ReactMethod
    public void cancelAlarm(int id) {
        AlarmManagerUtil.cancelAlarm(mReactContext, AlarmManagerUtil.ALARM_ACTION, id);
    }

    @Override
    public void onHostResume() {

    }

    @Override
    public void onHostPause() {

    }

    @Override
    public void onHostDestroy() {
        try{
            mReactContext.unregisterReceiver(mBroadcastReceiver);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
